package com.dly.hope.utils;

import jodd.util.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.Objects;

/**
 * @author linyu.dai
 * @project myserve
 * @description File工具类
 * @creat 2022/8/28 17:42:20
 */
@Slf4j
public class FileUtil {


    /**
     * 创建一个空的临时文件
     */
    public static File createEmptyTempFile(String key) {

        try {
            String path = System.getProperty("java.io.tmpdir");

            File temp = new File(path, key);

            if (temp.exists()) {
                temp.delete();
            }
            temp.createNewFile();

            return temp;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 通过url构建文件
     * @param url
     * @return
     */
    public static File downloadTempFile(String url) {

        try {
            File file = jodd.io.FileUtil.createTempFile();

            URL theUrl = new URL(url);
            ReadableByteChannel rbc = Channels.newChannel(theUrl.openStream());
            FileOutputStream fos = new FileOutputStream(file);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
            fos.close();
            rbc.close();
            return file;

        } catch (Exception e) {
            log.error(FileUtil.class.getSimpleName(), e);
            throw new RuntimeException(e);
        }

    }

    /**
     * @Author linyu.dai
     * @Description 邮件发送的附件_流控制_删除文件
     * @Date 2022/8/28 17:44
     * @Param [file]
     * @return void
     */
    public static void delete(File file) {
        try {

            if (null != file && file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @Author linyu.dai
     * @Description 通过文件全名字获取文件后缀
     * @Date 2022/8/30 11:28
     * @Param [fileName]
     * @return java.lang.String
     */
    public static String getFileSuffix(String fileName){
        //为空返回空字符串
        if(Objects.isNull(fileName) || fileName.lastIndexOf(StringPool.DOT)==-1){
            return StringPool.EMPTY;
        }else{
            return fileName.substring(fileName.lastIndexOf(StringPool.DOT)+1);
        }
    }

    /**
     * @Author linyu.dai
     * @Description 通过文件全名获取文件名字
     * @Date 2022/8/30 11:28
     * @Param [fileName]
     * @return java.lang.String
     */
    public static String getFilePrefix(String fileName){
        //为空返回空字符串
        if(Objects.isNull(fileName)){
            return StringPool.EMPTY;
        }
        if(fileName.lastIndexOf(StringPool.DOT)==-1){
            return fileName;
        }else{
            return fileName.substring(0 ,fileName.lastIndexOf(StringPool.DOT));
        }
    }
}
